package com.dhcc.bpm.modules.workflow.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.dhcc.bpm.common.config.AppEmailConfig;
import com.dhcc.bpm.common.config.AppTokenConfig;
import com.dhcc.bpm.common.enums.ConfigType;
import com.dhcc.bpm.common.redisMessage.RedisMessageSender;
import com.dhcc.bpm.common.text.Convert;
import com.dhcc.bpm.common.utils.*;
import com.dhcc.bpm.modules.api.entity.*;
import com.dhcc.bpm.modules.api.service.*;
import com.dhcc.bpm.modules.api.vo.ApiListVo;
import com.dhcc.bpm.modules.api.vo.ProdListVo;
import com.dhcc.bpm.modules.api.vo.productListVo;
import com.dhcc.bpm.modules.content.entity.DocDirectory;
import com.dhcc.bpm.modules.content.entity.Message;
import com.dhcc.bpm.modules.content.service.IDocDirectoryService;
import com.dhcc.bpm.modules.content.service.IMessageService;
import com.dhcc.bpm.modules.content.service.ISuggestionService;
import com.dhcc.bpm.modules.gateway.service.IGatewayRouteService;
import com.dhcc.bpm.modules.gateway.service.IGatewayService;
import com.dhcc.bpm.modules.orga.entity.*;
import com.dhcc.bpm.modules.orga.service.*;
import com.dhcc.bpm.modules.orga.vo.*;
import com.dhcc.bpm.modules.system.entity.Dict;
import com.dhcc.bpm.modules.system.service.IDictService;
import com.dhcc.bpm.modules.system.service.ISerialNumberService;
import com.dhcc.bpm.modules.system.service.IUserService;
import com.dhcc.bpm.modules.workflow.controller.CompareTwoClass;
import com.dhcc.bpm.modules.workflow.controller.XmlData;
import com.dhcc.bpm.modules.workflow.dto.ApiBO;
import com.dhcc.bpm.modules.workflow.entity.Approve;
import com.dhcc.bpm.modules.workflow.mapper.ApproveMapper;
import com.dhcc.bpm.modules.workflow.service.IApproveService;
import com.dhcc.bpm.modules.workflow.vo.ApproveVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName ApproveServiceImpl
 * @Description 工作流审批表 服务实现类
 * @Author YZC
 * @Date 2019/11/19 14:46
 * @Version V1.0
 * @Copyright: 2020 东华软件股份有限公司. All rights reserved.
 */
@Service
public class ApproveServiceImpl extends BaseServiceImpl<ApproveMapper, Approve> implements IApproveService {
    private final static Logger log = LoggerFactory.getLogger(ApproveServiceImpl.class);
    @Value("${bpm.approval.isApproval}")
    boolean isApproval;
    @Autowired
    private TokenStore tokenStore;
    @Autowired
    private IOrgaService orgaService;
    @Autowired
    private IApiService apiService;
    @Autowired
    private IIssueApiService issueApiService;
    @Autowired
    private IProductService productService;
    @Autowired
    private IAppService appService;
    @Autowired
    private ISerialNumberService serialNumberService;
    @Autowired
    private IProduceApplyService produceApplyService;
    @Autowired
    private ITestApplyService testApplyService;
    @Autowired
    private IGatewayService gatewayService;
    @Autowired
    private IGatewayRouteService gatewayRouteService;
    @Autowired
    private IOnlineApplyService onlineApplyService;
    @Autowired
    private IProductApiService productApiService;
    @Autowired
    private IDocDirectoryService iDocDirectoryService;
    @Autowired
    private ISysService sysService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IDictService dictService;
    @Autowired
    private IAppApiService appApiService;
    @Autowired
    private AppTokenConfig appTokenConfig;
    @Autowired
    private RedisMessageSender redisMessageSender;
    @Autowired
    private ISuggestionService suggestionService;
    @Autowired
    private IMessageService messageService;
    @Autowired
    private IBaseProductService baseProductService;
    @Autowired
    private AppEmailConfig appEmailConfig;
    @Autowired
    private EmailUtils emailUtils;
    @Value("${workflow.flow-url}")
    private String workflow_flow_url;
    @Value("${bpm.approval.isSendMail}")
    private boolean isSendFlag;
    @Override
    public IPage<ApproveVO> selectApprovePage(IPage<ApproveVO> page, ApproveVO approve) {
        return page.setRecords(baseMapper.selectApprovePage(page, approve));
    }


    @Override
    public R commitTask(ApproveVO approve) {
        Long id = approve.getId();
        String type = approve.getType();
        ResultAPI data = null;
        String url = "/" + type;
        switch (type) {
            case "api":
                //api发布类型
                String appType = approve.getAppType();
                //api批量发布id
                String apiIds = approve.getIds();
                //API发布
                data = selectApiInfo(approve);
                Head head = data.getHead();
                //返回响应码
                String responseCode = head.getResponseCode();
                if ("9999".equals(responseCode)){
                    return R.fail("此操作用户在系统中不存在!");
                }
                if ("0".equals(responseCode)) {
                    //返回流程ID
                    Object body = data.getBody();
                    Long processId = Long.valueOf(body.toString());
                    String code = serialNumberService.generateSerialNumberByModelCode("opc_issue_api");
                    Long[] api = Convert.toLongArray(apiIds);
                    Api apis = new Api();
                    IssueApi issueApiQuery = new IssueApi();
                    Approve appro = new Approve();
                    if ("1".equals(appType)){
                        for (Long datas : api) {
                            //查询是否有这条数据
                            IssueApi issueApi = issueApiService.selectByApiId(datas);
                            if (issueApi !=null){
                                issueApiService.remove(Condition.getQueryWrapper(issueApi));
                            }
                            //改变发布审核中
                            apis.setId(datas);
                            issueApiQuery.setId(Long.valueOf(code));
                            issueApiQuery.setApiId(datas);
                            //上线待审批
                            apis.setStatus(0);
                            issueApiQuery.setApprovalStatus(0);
                            appro.setUrl(url+"/up");
                            apiService.updateById(apis);
                            //中间表插入数据状态为审核中
                            issueApiService.save(issueApiQuery);
                        }
                    }else{
                        //有原纪录先删除
                        IssueApi issueApi = issueApiService.selectByApiId(id);
                        if (issueApi !=null){
                            issueApiService.remove(Condition.getQueryWrapper(issueApi));
                        }
                        //下线待审批
                        apis.setId(id);
                        apis.setStatus(5);
                        issueApiQuery.setId(Long.valueOf(code));
                        issueApiQuery.setApiId(id);
                        issueApiQuery.setApprovalStatus(5);
                        appro.setUrl(url+"/down");
                        apiService.updateById(apis);
                        //中间表插入数据状态为审核中
                        issueApiService.save(issueApiQuery);
                    }
                    //插入数据到审批表
                    appro.setBusNo(Long.valueOf(code));
                    appro.setApprovalStatus(0L);
                    appro.setProcessId(processId);
                    appro.setType(type);
                    save(appro);
                } else {
                    return R.status(false);
                }
                break;
            case "orga":
                //机构认证
                data = selectOrga(approve);
                Head head1 = data.getHead();
                //返回响应码
                String responseCode1 = head1.getResponseCode();
                if ("9999".equals(responseCode1)){
                    return R.fail("此操作用户在系统中不存在!");
                }
                //插入数据到审批表并且显示审核中
                if (!insertApprove(data, id, type, url)) {
                    return R.status(false);
                }else{
                    //成功后改变审批状态
                    Orga orga = new Orga();
                    orga.setId(id);
                    orga.setAuthFlag("3");
                    orgaService.updateById(orga);
                }
                break;
            case "orgaChange":
                //机构变更
                data = selectChangeOrga(approve);
                //返回响应码
                String responseCodeChange = data.getHead().getResponseCode();
                if ("9999".equals(responseCodeChange)){
                    return R.fail("此操作用户在系统中不存在!");
                }
                if (!insertApprove(data, id, type, url)) {
                    return R.status(false);
                }else{
                    //成功后改变审批状态
                    Orga newOrga = new Orga();
                    newOrga.setId(id);
                    newOrga.setAuthFlag("3");
                    orgaService.updateById(newOrga);
                }
                break;
            case "app":
                //渠道申请
                selectApp(approve);
                break;
            case "appChange":
                //渠道变更
                selectChangeApp(approve);
                break;
            case "produceapply":
                //生产环境
                selectProduceApply(approve);
                break;
            case "onlineapply":
                //生产切割
                selectOnlineapply(approve);
                break;
            default:
                break;
        }
        return R.status(true);
    }

    /**
     * @param data
     * @param id
     * @param type
     * @return java.lang.Boolean
     * @Description 插入数据到流程审核表
     * @Author sjm
     * @Date 9:12 2020/2/27 0027
     **/
    private Boolean insertApprove(ResultAPI data, Long id, String type, String url) {
        Head head = data.getHead();
        //返回响应码
        String responseCode = head.getResponseCode();
        if ("0".equals(responseCode)) {
            //返回流程ID
            Object body = data.getBody();
            Long processId = Long.valueOf(body.toString());

            ApproveVO appro = baseMapper.getApproById(id);
            if (appro !=null){
                //说明存在原记录，进行变更 (未通过再次发起审批)
                appro.setApprovalStatus(0L);
                appro.setProcessId(processId);
                baseMapper.updateById(appro);
            }else{
                //新增审批数据
                Approve approve = new Approve();
                approve.setBusNo(id);
                approve.setApprovalStatus(0L);
                approve.setProcessId(processId);
                approve.setType(type);
                approve.setUrl(url);
                save(approve);
            }
            return true;
        } else {
            return false;
        }
    }

    /**
     * @Description 多产品插入审批表
     * @Author sjm
     * @Date 16:01 2020/3/31 0031
     * @param data
     * @param id
     * @param productId
     * @param type
     * @param url
     * @return java.lang.Boolean
     **/
    private Boolean insertProdApprove(ResultAPI data, Long id, Long productId, String type, String url) {
        Head head = data.getHead();
        //返回响应码
        String responseCode = head.getResponseCode();
        if ("0".equals(responseCode)) {
            //返回流程ID
            Object body = data.getBody();
            Long processId = Long.valueOf(body.toString());

            Approve appros = baseMapper.getApproByProdAppId(id, productId);
            if (appros !=null){
                //说明有原数据（未通过重新发起）
                appros.setApprovalStatus(0L);
                appros.setProcessId(processId);
                baseMapper.updateById(appros);
            }else{
                Approve approve = new Approve();
                approve.setBusNo(id);
                approve.setProductId(productId);
                approve.setApprovalStatus(0L);
                approve.setProcessId(processId);
                approve.setType(type);
                approve.setUrl(url);
                save(approve);
            }
            return true;
        } else {
            return false;
        }
    }

    /**
     * @param approve
     * @return com.dhcc.bpm.common.utils.ResultAPI
     * @Description 生产切割
     * @Author sjm
     * @Date 17:20 2020/3/7 0007
     **/
    private R selectOnlineapply(ApproveVO approve) {
        Long id = approve.getId();
        OnlineApply onlineApply = onlineApplyService.getById(id);
        //查询机构信息
        OrgaTestVo org = orgaService.selectOrgaTest(onlineApply.getOrgaId());
        org.setOrgaTypeDesc(dictService.getValue("orga_type", String.valueOf(org.getOrgaType())));
        org.setServiceTradeDesc(dictService.getValue("industry_type", String.valueOf(org.getServiceTrade())));
        if (org.getIsDomestic() != null && !("").equals(org.getIsDomestic())) {
            org.setIsDomesticDesc(dictService.getValue("area_list", String.valueOf(org.getIsDomestic())));
        } else {
            org.setIsDomestic("");
            org.setIsDomesticDesc("");
        }
        //查询申请生产切割数据
        AppOnlineVo appOnlineVo = onlineApplyService.selectAppById(id);
        //查询产品信息集合
        List<ProdListVo> prodListVo = productService.selectProdList(onlineApply.getAppId());
        //生产切割接口路径
        String path = "/CeairDevService/ApiAuditNDC/ApiAuditNdcService.asmx/StartProduceCutFlow";
        String resData = "";
        for(ProdListVo prod: prodListVo) {
            prod.setPrivilegeLevelDesc(dictService.getValue("privilege_level", String.valueOf(prod.getPrivilegeLevel())));
            prod.setIsCostDesc(dictService.getValue("is_cost", String.valueOf(prod.getIsCost())));
            if (prod.getNote() == null) {
                prod.setNote("");
            }
        }
        Map<String, List<ProdListVo>> map = prodListVo.stream().collect(Collectors.groupingBy(ProdListVo::getOwnSystem));
        for (Map.Entry<String, List<ProdListVo>> m : map.entrySet()) {
            String sysName = m.getKey();
            List<ProdListVo> list = m.getValue();
            ArrayList<ProdListVo> prolist = new ArrayList<>();
            for(ProdListVo data: list){
                prolist.add(data);
            }
            //产品类型
            String prodType = (("AI系统").equals(sysName)? "2": (("NDC系统").equals(sysName)? "1": "3"));
            //公共标题pub
            HashMap<String, String> hashMap = new HashMap();
            hashMap.put("title", "申请生产切割");
            hashMap.put("busNo", String.valueOf(id));
            hashMap.put("appType", "1");
            hashMap.put("appTypeDesc", "申请生产切割");
            hashMap.put("mode",approve.getModeType());
            hashMap.put("modeDesc",approve.getModeTypeDesc());
            hashMap.put("useruid",approve.getUseruid());
            hashMap.put("account",approve.getAccount());
            hashMap.put("realName",approve.getRealName());
            hashMap.put("prodType",prodType);
            hashMap.put("prodTypeName",sysName);
            //组请求报文
            HashMap<String, Object> map1 = new HashMap();
            map1.put("org", org);
            Map<String, Object> orgMap = new LinkedHashMap<String, Object>();
            orgMap.put("pub", hashMap);
            orgMap.put("orgData", map1);
            orgMap.put("appSwitchInfo", appOnlineVo);
            orgMap.put("productList", prolist);
            Map<String, Object> mapHead = new LinkedHashMap<>();
            Map<String, Object> postParameters = new LinkedHashMap<>();
            postParameters.put("Head", mapHead);
            postParameters.put("Body", orgMap);
            try {
                //返回响应报文
                resData = XmlData.getXml(path, postParameters);
            } catch (IOException e) {
                log.error("异常信息：{}", e);
            }
            //响应报文转成对象
            ResultAPI data = JSONObject.parseObject(resData, ResultAPI.class);
            //返回响应码
            String responseCode = data.getHead().getResponseCode();
            if ("9999".equals(responseCode)){
                return R.fail("此操作用户在系统中不存在!");
            }
            String type = approve.getType();
            String url = "/" + type;
            //根据系统名称查询id
            Sys sys = sysService.selectByName(sysName);
            Long productId = sys.getId();
            if (!insertProdApprove(data, id, productId, type, url)) {
                return R.status(false);
            }
        }
        //发起审批成功后改变状态
        onlineApply.setApproveStatus("4");
        onlineApply.setApproveOpinion("");
        onlineApplyService.updateById(onlineApply);
        return R.status(true);
    }

    /**
     * @param approve
     * @return com.dhcc.bpm.common.utils.ResultAPI
     * @Description 生产环境
     * @Author sjm
     * @Date 17:20 2020/3/7 0007
     **/
    private R selectProduceApply(ApproveVO approve) {
        Long id = approve.getId();
        //赋值新数据
        ProduceApply produceApply = produceApplyService.getById(id);
        if(isApproval){
            produceApply.setBeginTimeNew(approve.getTestBeginTime());
            produceApply.setEndTimeNew(approve.getTestEndTime());
            produceApply.setApplyFlow(String.valueOf(approve.getApplyQps()));
            produceApply.setApprovalFlow(String.valueOf(approve.getApprovalQps()));
            produceApplyService.updateById(produceApply);
        }

        //查询机构信息
        OrgaTestVo org = orgaService.selectOrgaTest(produceApply.getOrgaId());
        org.setOrgaTypeDesc(dictService.getValue("orga_type", String.valueOf(org.getOrgaType())));
        org.setServiceTradeDesc(dictService.getValue("industry_type", String.valueOf(org.getServiceTrade())));
        if (org.getIsDomestic() != null && !("").equals(org.getIsDomestic())) {
            org.setIsDomesticDesc(dictService.getValue("area_list", String.valueOf(org.getIsDomestic())));
        } else {
            org.setIsDomestic("");
            org.setIsDomesticDesc("");
        }
        //查询申请测试信息
        AppProduceVo appProduceVo = produceApplyService.selectProcueById(id);
        //合同照片转base64
        String contract = appProduceVo.getContract();
        String path1 = contract.substring(0,contract.lastIndexOf("/")+1);
        String name = contract.substring(contract.lastIndexOf("/") + 1);
        String imgContract = null;
        try {
            imgContract = ImgUtil.getImageBinary(path1,name);
        } catch (Exception e) {
            e.printStackTrace();
        }
        appProduceVo.setContract(imgContract);
        if (appProduceVo.getApplyFlow() == null){
            appProduceVo.setApplyFlow(0L);
        }
        if(appProduceVo.getApprovalFlow() == null){
            appProduceVo.setApprovalFlow(0L);
        }
        //赋值新数据
        if(produceApply != null && isApproval){
            appProduceVo.setTestBeginTime(produceApply.getBeginTimeNew());
            appProduceVo.setTestEndTime(produceApply.getEndTimeNew());
            appProduceVo.setApplyQps(Long.valueOf(produceApply.getApplyFlow()));
            appProduceVo.setApprovalQps(Long.valueOf(produceApply.getApprovalFlow()));
        }
        appProduceVo.setDescribe("");
        appProduceVo.setPayMentDesc(dictService.getValue("pay_ment", String.valueOf(appProduceVo.getPayMent())));

        //生产环境接口路径
        String path = "/CeairDevService/ApiAuditNDC/ApiAuditNdcService.asmx/StartProduceEnvironFlow";
        String resData = "";
        List<ProdListVo> prodListVo = productService.selectProdList(produceApply.getAppId());
        for (ProdListVo prod: prodListVo) {
            prod.setPrivilegeLevelDesc(dictService.getValue("privilege_level", String.valueOf(prod.getPrivilegeLevel())));
            prod.setIsCostDesc(dictService.getValue("is_cost", String.valueOf(prod.getIsCost())));
            if (prod.getNote() == null) {
                prod.setNote("");
            }
        }
        Map<String, List<ProdListVo>> map = prodListVo.stream().collect(Collectors.groupingBy(ProdListVo::getOwnSystem));
        for (Map.Entry<String, List<ProdListVo>> m : map.entrySet()) {
            String sysName = m.getKey();
            List<ProdListVo> list = m.getValue();
            ArrayList<ProdListVo> prolist = new ArrayList<>();
            for(ProdListVo data: list){
                prolist.add(data);
            }
            //产品类型
            String prodType = (("AI系统").equals(sysName)? "2": (("NDC系统").equals(sysName)? "1": "3"));
            //公共pub标题
            HashMap<String, String> hashMap = new HashMap();
            hashMap.put("title", "申请生产环境");
            hashMap.put("busNo", String.valueOf(id));
            hashMap.put("appType", "1");
            hashMap.put("appTypeDesc", "申请生产环境");
            hashMap.put("mode",approve.getModeType());
            hashMap.put("modeDesc",approve.getModeTypeDesc());
            hashMap.put("useruid",approve.getUseruid());
            hashMap.put("account",approve.getAccount());
            hashMap.put("realName",approve.getRealName());
            hashMap.put("prodType",prodType);
            hashMap.put("prodTypeName",sysName);
            HashMap<String, Object> map1 = new HashMap();
            map1.put("org", org);
            Map<String, Object> orgMap = new LinkedHashMap<String, Object>();
            orgMap.put("pub", hashMap);
            orgMap.put("orgData", map1);
            orgMap.put("appProInfo", appProduceVo);
            orgMap.put("productList", prolist);
            Map<String, Object> mapHead = new LinkedHashMap<>();
            Map<String, Object> postParameters = new LinkedHashMap<>();
            postParameters.put("Head", mapHead);
            postParameters.put("Body", orgMap);
            try {
                //返回响应报文
                resData = XmlData.getXml(path, postParameters);
            } catch (IOException e) {
                log.error("异常信息：{}", e);
            }
            //响应报文转成对象
            ResultAPI data = JSONObject.parseObject(resData, ResultAPI.class);
            //返回响应码
            String responseCode = data.getHead().getResponseCode();
            if ("9999".equals(responseCode)){
                return R.fail("此操作用户在系统中不存在!");
            }
            String type = approve.getType();
            String url = "/" + type;
            //根据系统名称查询id
            Sys sys = sysService.selectByName(sysName);
            Long productId = sys.getId();
            if (!insertProdApprove(data, id, productId, type, url)) {
                return R.status(false);
            }
        }
        //发起审批成功后改变审批状态
        produceApply.setApproveStatus("4");
        produceApply.setApproveOpinion("");
        produceApplyService.updateById(produceApply);
        return R.status(true);
    }

    /**
     * @param approve
     * @return com.dhcc.bpm.common.utils.ResultAPI
     * @Description 机构变更
     * @Author sjm
     * @Date 17:20 2020/3/7 0007
     **/
    private ResultAPI selectChangeOrga(ApproveVO approve) {
        Long id = approve.getId();
        Orga orga = orgaService.getById(id);
        //查询变更后机构信息
        OrgaInfoNewVo newOrg = orgaService.selectOrgaInfoNew(id);
        //截取新的文件名
        String otherFilesNew = newOrg.getOtherFilesNew();
        String otherFilesNameNew = otherFilesNew.substring(otherFilesNew.lastIndexOf("/") + 1);
        newOrg.setOtherFilesNameNew(otherFilesNameNew);
        newOrg.setOrgaTypeDescNew(dictService.getValue("orga_type", String.valueOf(newOrg.getOrgaTypeNew())));
        newOrg.setServiceTradeDescNew(dictService.getValue("industry_type", String.valueOf(newOrg.getServiceTradeNew())));
        if (newOrg.getIsDomesticNew() != null) {
            newOrg.setIsDomesticDescNew(dictService.getValue("area_list", String.valueOf(newOrg.getIsDomesticNew())));
        } else {
            newOrg.setIsDomesticNew("");
            newOrg.setIsDomesticDescNew("");
        }
        //IATA证书 和 营业执照Base64
        String officialLetterNew = newOrg.getOfficialLetterNew();
        String imageBinaryNew = null;
        try {
            imageBinaryNew = ImgUtil.ImageToBase64(officialLetterNew);
        } catch (Exception e) {
            log.error("异常信息：{}", e);
        }
        log.info("变更后证书base64:" + imageBinaryNew);
        if(imageBinaryNew != null){
            //将二进制进行编码处理
            newOrg.setOfficialLetterNew(base64ToEncode(imageBinaryNew));
        }else {
            newOrg.setOfficialLetterNew("");
        }
        String busLicenceNew = newOrg.getBusLicenceNew();
        String busBinaryNew = null;
        try {
            busBinaryNew = ImgUtil.ImageToBase64(busLicenceNew);
        } catch (Exception e) {
            log.error("异常信息：{}", e);
        }
        log.info("变更后营业执照Base64:" + imageBinaryNew);
        if(busBinaryNew != null){
            //将二进制进行编码处理
            newOrg.setBusLicenceNew(base64ToEncode(busBinaryNew));
        }else {
            newOrg.setBusLicenceNew("");
        }
        //查询变更后注册联系人
        OrgaManNewVo newRegInfo = orgaService.selectManNew(id);
        newRegInfo.setAuthDocumentTypeDescNew(dictService.getValue("cert_type", String.valueOf(newRegInfo.getAuthDocumentTypeNew())));
        //查询变更后其他注册联系人
        OrgaOtherManNewVo newOtherRegInfo = orgaService.selectOtherManNew(id);
        if (newOtherRegInfo.getOtherPerChargeNew() == null){
            newOtherRegInfo.setOtherPerChargeNew("");
        }
        if (newOtherRegInfo.getOtherPerNumberNew() == null){
            newOtherRegInfo.setOtherPerNumberNew("");
        }
        if (newOtherRegInfo.getOtherInvoiceMailingAddrNew() == null){
            newOtherRegInfo.setOtherInvoiceMailingAddrNew("");
        }
        if (newOtherRegInfo.getOtherAuthDocumentNumNew() == null){
            newOtherRegInfo.setOtherAuthDocumentNumNew("");
        }
        if (newOtherRegInfo.getOtherAuthDocumentTypeNew() != null) {
            newOtherRegInfo.setOtherAuthDocumentTypeDescNew(dictService.getValue("cert_type", String.valueOf(newOtherRegInfo.getOtherAuthDocumentTypeNew())));
        }else{
            newOtherRegInfo.setOtherAuthDocumentTypeNew("");
            newOtherRegInfo.setOtherAuthDocumentTypeDescNew("");
        }
        //查询变更前信息
        OrgaInfoVo oldOrg = orgaService.selectOrgaInfo(orga.getParentId());
        //截取文件名
        String otherFiles = oldOrg.getOtherFiles();
        String otherFilesName = otherFiles.substring(otherFiles.lastIndexOf("/") + 1);
        oldOrg.setOtherFilesName(otherFilesName);
        //转义机构信息变更前描述字段
        if (oldOrg.getIsDomestic() != null) {
            oldOrg.setIsDomesticDesc(dictService.getValue("area_list", String.valueOf(oldOrg.getIsDomestic())));
        } else {
            oldOrg.setIsDomestic("");
            oldOrg.setIsDomesticDesc("");
        }
        oldOrg.setOrgaTypeDesc(dictService.getValue("orga_type", String.valueOf(oldOrg.getOrgaType())));
        oldOrg.setServiceTradeDesc(dictService.getValue("industry_type", String.valueOf(oldOrg.getServiceTrade())));
        //变更前IATA证书 和 营业执照Base64
        String officialLetter = oldOrg.getOfficialLetter();
        String imageBinary = null;
        try {
            imageBinary = ImgUtil.ImageToBase64(officialLetter);
        } catch (Exception e) {
            log.error("异常信息：{}", e);
        }
        log.info("变更前证书：" + imageBinary);
        if(imageBinary != null){
            //将二进制进行编码处理
            oldOrg.setOfficialLetter(base64ToEncode(imageBinary));
        }else {
            oldOrg.setOfficialLetter("");
        }
        String busLicence = oldOrg.getBusLicence();
        String busBinary = null;
        try {
            busBinary = ImgUtil.ImageToBase64(busLicence);
        } catch (Exception e) {
            log.error("异常信息：{}", e);
        }
        log.info("变更前营业执照Base64：" + imageBinary);
        if(busBinary != null){
            //将二进制进行编码处理
            oldOrg.setBusLicence(base64ToEncode(busBinary));
        }else {
            oldOrg.setBusLicence("");
        }
        OrgaInfoVo newOrgaChange = orgaService.selectOrgaInfo(id);
        //转义变更后描述字段
        if (newOrgaChange.getIsDomestic() != null) {
            newOrgaChange.setIsDomesticDesc(dictService.getValue("area_list", String.valueOf(newOrgaChange.getIsDomestic())));
        } else {
            newOrgaChange.setIsDomestic("");
            newOrgaChange.setIsDomesticDesc("");
        }
        newOrgaChange.setOrgaTypeDesc(dictService.getValue("orga_type", String.valueOf(newOrgaChange.getOrgaType())));
        newOrgaChange.setServiceTradeDesc(dictService.getValue("industry_type", String.valueOf(newOrgaChange.getServiceTrade())));
        OrgaManVo oldRegInfo = orgaService.selectMan(orga.getParentId());
        OrgaManVo newregInfo = orgaService.selectMan(id);
        //转义描述字段
        oldRegInfo.setAuthDocumentTypeDesc(dictService.getValue("cert_type", String.valueOf(oldRegInfo.getAuthDocumentType())));
        newregInfo.setAuthDocumentTypeDesc(dictService.getValue("cert_type", String.valueOf(newregInfo.getAuthDocumentType())));

        OrgaOtherManVo oldOtherRegInfo = orgaService.selectOtherMan(orga.getParentId());
        OrgaOtherManVo newotherRegInfo = orgaService.selectOtherMan(id);
        if (oldOtherRegInfo.getOtherPerCharge() == null){
            oldOtherRegInfo.setOtherPerCharge("");
        }
        if (oldOtherRegInfo.getOtherPerNumber() == null){
            oldOtherRegInfo.setOtherPerNumber("");
        }
        if (oldOtherRegInfo.getOtherInvoiceMailingAddr() == null){
            oldOtherRegInfo.setOtherInvoiceMailingAddr("");
        }
        if (oldOtherRegInfo.getOtherAuthDocumentNum() == null){
            oldOtherRegInfo.setOtherAuthDocumentNum("");
        }
        if (oldOtherRegInfo.getOtherAuthDocumentType() != null) {
            oldOtherRegInfo.setOtherAuthDocumentTypeDesc(dictService.getValue("cert_type", String.valueOf(oldOtherRegInfo.getOtherAuthDocumentType())));
        }else{
            oldOtherRegInfo.setOtherAuthDocumentType("");
            oldOtherRegInfo.setOtherAuthDocumentTypeDesc("");
        }

        //变更后比较
        if (newotherRegInfo.getOtherPerCharge() == null){
            newotherRegInfo.setOtherPerCharge("");
        }
        if (newotherRegInfo.getOtherPerNumber() == null){
            newotherRegInfo.setOtherPerNumber("");
        }
        if (newotherRegInfo.getOtherInvoiceMailingAddr() == null){
            newotherRegInfo.setOtherInvoiceMailingAddr("");
        }
        if (newotherRegInfo.getOtherAuthDocumentNum() == null){
            newotherRegInfo.setOtherAuthDocumentNum("");
        }
        if (newotherRegInfo.getOtherAuthDocumentType() != null) {
            newotherRegInfo.setOtherAuthDocumentTypeDesc(dictService.getValue("cert_type", String.valueOf(newotherRegInfo.getOtherAuthDocumentType())));
        }else{
            newotherRegInfo.setOtherAuthDocumentType("");
            newotherRegInfo.setOtherAuthDocumentTypeDesc("");
        }
        //利用反射比较
        List<Map<Object, Object>> orgList = null;
        List<Map<Object, Object>> InfoList = null;
        List<Map<Object, Object>> otherRegInfoList = null;
        try {
            orgList = CompareTwoClass.compareTwoClass(oldOrg, newOrgaChange);
            InfoList = CompareTwoClass.compareTwoClass(oldRegInfo, newregInfo);
            otherRegInfoList = CompareTwoClass.compareTwoClass(oldOtherRegInfo, newotherRegInfo);
        } catch (ClassNotFoundException e) {
            log.error("异常信息：{}", e);
        } catch (IllegalAccessException e) {
            log.error("异常信息：{}", e);
        }
        if (orgList == null) {
            orgList = null;
        }
        if (InfoList == null) {
            InfoList = null;
        }
        if (otherRegInfoList == null) {
            otherRegInfoList = null;
        }
        Map<String, Object> orgChangeMap = new LinkedHashMap<String, Object>();
        orgChangeMap.put("orgChange", orgList);
        orgChangeMap.put("infoChange", InfoList);
        orgChangeMap.put("otherChange", otherRegInfoList);
        Map<String, Object> oldMap = new LinkedHashMap<String, Object>();
        oldMap.put("org", oldOrg);
        oldMap.put("regInfo", oldRegInfo);
        oldMap.put("otherRegInfo", oldOtherRegInfo);
        Map<String, Object> newMap = new LinkedHashMap<String, Object>();
        newMap.put("org", newOrg);
        newMap.put("regInfo", newRegInfo);
        newMap.put("otherRegInfo", newOtherRegInfo);
        //公共标题
        HashMap<String, String> hashMap = new HashMap();
        hashMap.put("title", "机构变更");
        hashMap.put("busNo", String.valueOf(id));
        hashMap.put("appType", "2");
        hashMap.put("appTypeDesc", "机构变更");
        hashMap.put("mode",approve.getModeType());
        hashMap.put("modeDesc",approve.getModeTypeDesc());
        hashMap.put("useruid",approve.getUseruid());
        hashMap.put("account",approve.getAccount());
        hashMap.put("realName", approve.getRealName());
        Map<String, Object> orgaChangeMap = new LinkedHashMap<String, Object>();
        orgaChangeMap.put("pub", hashMap);
        orgaChangeMap.put("orgData", oldMap);
        orgaChangeMap.put("orgChangeData", newMap);
        orgaChangeMap.put("ChangeData", orgChangeMap);
        Map<String, Object> mapHead = new LinkedHashMap<>();
        Map<String, Object> postParameters = new LinkedHashMap<>();
        postParameters.put("Head", mapHead);
        postParameters.put("Body", orgaChangeMap);
        //机构变更接口路径
        String path = "/CeairDevService/ApiAuditNDC/ApiAuditNdcService.asmx/StartApiProSubChangeFlow";
        String resData = "";
        try {
            //返回响应报文
            resData = XmlData.getXml(path, postParameters);
        } catch (IOException e) {
            log.error("异常信息：{}", e);
        }
        //响应报文转成对象
        ResultAPI data = JSONObject.parseObject(resData, ResultAPI.class);
        return data;
    }

    private String base64ToEncode(String imgText) {
        Base64.Encoder encoder = Base64.getEncoder();
        byte[] textByte = null;
        try {
            textByte = imgText.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            log.error("异常信息：{}", e);
        }
        String encodedText = encoder.encodeToString(textByte);
        log.info("图片编码：" +encodedText);
        return encodedText;
    }

    /**
     * @param approve
     * @return com.dhcc.bpm.common.utils.ResultAPI
     * @Description 渠道变更
     * @Author sjm
     * @Date 17:31 2020/3/7 0007
     **/
    private R selectChangeApp(ApproveVO approve){
        Long id = approve.getId();
        //变更后渠道数据
        App app = appService.getById(id);
        TestApply testApplyDetail = null;
        if(isApproval){
            //赋值测试有效期
            TestApply testApply = new TestApply();
            testApply.setAppId(app.getPid());
            testApplyDetail = testApplyService.getOne(Condition.getQueryWrapper(testApply));
            testApplyDetail.setBeginTimeNew(approve.getTestBeginTime());
            testApplyDetail.setEndTimeNew(approve.getTestEndTime());
            testApplyDetail.setApplyFlow(String.valueOf(approve.getApplyQps()));
            testApplyDetail.setApprovalFlow(String.valueOf(approve.getApprovalQps()));
            testApplyService.updateById(testApplyDetail);
        }

        //查询机构信息
        OrgaInfoVo org = orgaService.selectOrgaInfo(app.getOpcOrgaId());
        //截取文件名
        String otherFiles = org.getOtherFiles();
        String otherFilesName = otherFiles.substring(otherFiles.lastIndexOf("/") + 1);
        org.setOtherFilesName(otherFilesName);
        org.setOrgaTypeDesc(dictService.getValue("orga_type", String.valueOf(org.getOrgaType())));
        org.setServiceTradeDesc(dictService.getValue("industry_type", String.valueOf(org.getServiceTrade())));
        if (org.getIsDomestic() != null) {
            org.setIsDomesticDesc(dictService.getValue("area_list", String.valueOf(org.getIsDomestic())));
        } else {
            org.setIsDomestic("");
            org.setIsDomesticDesc("");
        }
        //IATA证书 和 营业执照Base64
        String officialLetter = org.getOfficialLetter();
        String offPath = officialLetter.substring(0,officialLetter.lastIndexOf("/")+1);
        String offName = officialLetter.substring(officialLetter.lastIndexOf("/") + 1);
        String imageBinary = null;
        try {
            imageBinary = ImgUtil.getImageBinary(offPath, offName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        org.setOfficialLetter(imageBinary);
        String busLicence = org.getBusLicence();
        String busPath = busLicence.substring(0,busLicence.lastIndexOf("/")+1);
        String busName = busLicence.substring(busLicence.lastIndexOf("/") + 1);
        String busBinary = null;
        try {
            busBinary = ImgUtil.getImageBinary(busPath, busName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        org.setBusLicence(busBinary);
        //查询注册联系人
        OrgaManVo regInfo = orgaService.selectMan(app.getOpcOrgaId());
        regInfo.setAuthDocumentTypeDesc(dictService.getValue("cert_type", String.valueOf(regInfo.getAuthDocumentType())));
        //查询其他注册联系人
        OrgaOtherManVo otherRegInfo = orgaService.selectOtherMan(app.getOpcOrgaId());
        if (otherRegInfo.getOtherPerCharge() == null){
            otherRegInfo.setOtherPerCharge("");
        }
        if (otherRegInfo.getOtherPerNumber() == null){
            otherRegInfo.setOtherPerNumber("");
        }
        if (otherRegInfo.getOtherInvoiceMailingAddr() == null){
            otherRegInfo.setOtherInvoiceMailingAddr("");
        }
        if (otherRegInfo.getOtherAuthDocumentNum() == null){
            otherRegInfo.setOtherAuthDocumentNum("");
        }
        if (otherRegInfo.getOtherAuthDocumentType() != null) {
            otherRegInfo.setOtherAuthDocumentTypeDesc(dictService.getValue("cert_type", String.valueOf(otherRegInfo.getOtherAuthDocumentType())));
        }else{
            otherRegInfo.setOtherAuthDocumentType("");
            otherRegInfo.setOtherAuthDocumentTypeDesc("");
        }
        //查询变更前申请测试信息
        AppTestVo appTestVo = appService.selectAppInfo(app.getPid());
        if (appTestVo.getAppType() != null) {
            String appTypes = appTestVo.getAppType();
            appTestVo.setAppTypeDesc(getAppTypeNames(appTypes));
        }
        if (appTestVo.getPayMent() != null && !("").equals(appTestVo.getPayMent())) {
            appTestVo.setPayMentDesc(dictService.getValue("pay_ment", String.valueOf(appTestVo.getPayMent())));
        }
        if (appTestVo.getApplyFlow() == null){
            appTestVo.setApplyFlow(0L);
        }
        if (appTestVo.getApprovalFlow() == null){
            appTestVo.setApprovalFlow(0L);
        }
        if(testApplyDetail != null && isApproval){
            appTestVo.setTestBeginTime(testApplyDetail.getBeginTimeNew());
            appTestVo.setTestEndTime(testApplyDetail.getEndTimeNew());
            appTestVo.setApplyQps(Long.valueOf(testApplyDetail.getApplyFlow()));
            appTestVo.setApprovalQps(Long.valueOf(testApplyDetail.getApprovalFlow()));
        }

        AppTestVo newAppTestVo = appService.selectAppInfo(id);
        if (newAppTestVo.getAppType() != null) {
            String appTypes = appTestVo.getAppType();
            appTestVo.setAppTypeDesc(getAppTypeNames(appTypes));
        }
        if (newAppTestVo.getPayMent() != null && !("").equals(appTestVo.getPayMent())) {
            newAppTestVo.setPayMentDesc(dictService.getValue("pay_ment", String.valueOf(newAppTestVo.getPayMent())));
        }
        //利用反射比较
        List<Map<Object, Object>> appChangeList = null;
        try {
            appChangeList = CompareTwoClass.compareTwoClass(appTestVo, newAppTestVo);
        } catch (ClassNotFoundException e) {
            log.error("异常信息：{}", e);
        } catch (IllegalAccessException e) {
            log.error("异常信息：{}", e);
        }
        if (appChangeList.size() == 0) {
            appChangeList = null;
        }
        //查询变更后申请测试信息
        AppTestNewVo appTestNewVo = appService.selectAppInfoNew(id);
        if (appTestNewVo.getAppTypeNew() != null) {
            String appTypes = appTestNewVo.getAppTypeNew();
            appTestNewVo.setAppTypeDescNew(getAppTypeNames(appTypes));
        }
        if (appTestNewVo.getPayMentNew() != null && !("").equals(appTestNewVo.getPayMentNew())) {
            appTestNewVo.setPayMentDescNew(dictService.getValue("pay_ment", String.valueOf(appTestNewVo.getPayMentNew())));
        }else{
            appTestNewVo.setPayMentNew("");
            appTestNewVo.setPayMentDescNew("");
        }
        if (appTestNewVo.getApplyMsgNew() == null){
            appTestNewVo.setApplyMsgNew(appTestVo.getApplyMsg());
        }
        if (appTestNewVo.getIpNew() == null){
            appTestNewVo.setIpNew(appTestVo.getIp());
        }
        if (appTestNewVo.getTestBeginTimeNew() == null){
            appTestNewVo.setTestBeginTimeNew(appTestVo.getTestBeginTime());
        }
        if (appTestNewVo.getTestEndTimeNew() == null){
            appTestNewVo.setTestEndTimeNew(appTestVo.getTestEndTime());
        }
        if (appTestNewVo.getApplyFlowNew() == null){
            appTestNewVo.setApplyFlowNew(0L);
        }
        if (appTestNewVo.getApplyQpsNew() == null){
            appTestNewVo.setApplyQpsNew(appTestVo.getApplyQps());
        }
        if (appTestNewVo.getApprovalFlowNew() == null){
            appTestNewVo.setApprovalFlowNew(0L);
        }
        if (appTestNewVo.getApprovalQpsNew() == null){
            appTestNewVo.setApprovalQpsNew(appTestVo.getApprovalQps());
        }
        //查询产品信息集合 多产品分批发送审批
        //渠道变更接口路径
        String path = "/CeairDevService/ApiAuditNDC/ApiAuditNdcService.asmx/StartChaanelChangeFlow";
        String resData = "";
        List<ProdListVo> prodListVo = productService.selectProdList(id);
        for (ProdListVo prods : prodListVo) {
            prods.setPrivilegeLevelDesc(dictService.getValue("privilege_level",String.valueOf(prods.getPrivilegeLevel())));
            prods.setIsCostDesc(dictService.getValue("is_cost", String.valueOf(prods.getIsCost())));
            if (prods.getNote() == null) {
                prods.setNote("");
            }
        }
        Map<String, List<ProdListVo>> map = prodListVo.stream().collect(Collectors.groupingBy(ProdListVo::getOwnSystem));
        for (Map.Entry<String, List<ProdListVo>> m : map.entrySet()) {
            String sysName = m.getKey();
            List<ProdListVo> list = m.getValue();
            ArrayList<ProdListVo> prolist = new ArrayList<>();
            for(ProdListVo data: list){
                prolist.add(data);
            }
            //产品类型
            String prodType = (("AI系统").equals(sysName)? "2": (("NDC系统").equals(sysName)? "1": "3"));
            //发送pub公共部分
            HashMap<String, String> hashMap = new HashMap();
            hashMap.put("title", "渠道变更");
            hashMap.put("busNo", String.valueOf(id));
            hashMap.put("appType", "2");
            hashMap.put("appTypeDesc", "渠道变更");
            hashMap.put("mode",approve.getModeType());
            hashMap.put("modeDesc",approve.getModeTypeDesc());
            hashMap.put("useruid",approve.getUseruid());
            hashMap.put("account",approve.getAccount());
            hashMap.put("realName",approve.getRealName());
            hashMap.put("prodType",prodType);
            hashMap.put("prodTypeName",sysName);
            //组请求报文
            Map<String, Object> map1 = new LinkedHashMap<String, Object>();
            map1.put("org", org);
            map1.put("regInfo", regInfo);
            map1.put("otherRegInfo", otherRegInfo);
            HashMap<String, Object> map2 = new HashMap();
            map2.put("orgData", map1);
            HashMap<String, Object> oldmap = new HashMap();
            oldmap.put("appTestInfo", appTestVo);
            HashMap<String, Object> newmap = new HashMap();
            newmap.put("appTestInfo", appTestNewVo);
            HashMap<String, Object> map6 = new HashMap();
            map6.put("changeAppData", appChangeList);
            Map<String, Object> newApp = new LinkedHashMap<String, Object>();
            newApp.put("pub", hashMap);
            newApp.put("orgData", map1);
            newApp.put("chnlData", oldmap);
            newApp.put("chnlChangeData", newmap);
            newApp.put("chnlChangeAppData", map6);
            newApp.put("productList", prolist);
            Map<String, Object> mapHead = new LinkedHashMap<>();
            Map<String, Object> postParameters = new LinkedHashMap<>();
            postParameters.put("Head", mapHead);
            postParameters.put("Body", newApp);
            try {
                //返回响应报文
                resData = XmlData.getXml(path, postParameters);
            } catch (IOException e) {
                log.error("异常信息：{}", e);
            }
            //响应报文转成对象
            ResultAPI data = JSONObject.parseObject(resData, ResultAPI.class);
            //返回响应码
            String responseCode = data.getHead().getResponseCode();
            if ("9999".equals(responseCode)){
                return R.fail("此操作用户在系统中不存在!");
            }
            String type = approve.getType();
            String url = "/" + type;
            //根据系统名称查询id
            Sys sys = sysService.selectByName(sysName);
            Long productId = sys.getId();
            if (!insertProdApprove(data, id,productId, type, url)) {
                return R.status(false);
            }
        }
        //发起审批后改变状态
        app.setStatus(4);
        app.setApproveOpinion("");
        appService.updateById(app);
        return R.status(true);
    }

    /**
     * @param approve
     * @return com.dhcc.bpm.common.utils.ResultAPI
     * @Description 渠道申请
     * @Author sjm
     * @Date 17:36 2020/3/7 0007
     **/
    private R selectApp(ApproveVO approve) {
        Long id = approve.getId();
        App app = appService.getById(id);
        TestApply testApplyDetail = null;
        if (isApproval){
            //赋值测试有效期
            TestApply testApply = new TestApply();
            testApply.setAppId(id);
            testApplyDetail = testApplyService.getOne(Condition.getQueryWrapper(testApply));
            testApplyDetail.setBeginTimeNew(approve.getTestBeginTime());
            testApplyDetail.setEndTimeNew(approve.getTestEndTime());
            testApplyDetail.setApplyFlow(String.valueOf(approve.getApplyQps()));
            testApplyDetail.setApprovalFlow(String.valueOf(approve.getApprovalQps()));
            testApplyService.updateById(testApplyDetail);
        }

        //查询机构信息
        OrgaInfoVo org = orgaService.selectOrgaInfo(app.getOpcOrgaId());
        //截取文件名
        String otherFiles = org.getOtherFiles();
        if (otherFiles != null) {
            String otherFilesName = otherFiles.substring(otherFiles.lastIndexOf("/") + 1);
            org.setOtherFilesName(otherFilesName);
        }
        org.setOrgaTypeDesc(dictService.getValue("orga_type", String.valueOf(org.getOrgaType())));
        org.setServiceTradeDesc(dictService.getValue("industry_type", String.valueOf(org.getServiceTrade())));
        if (org.getIsDomestic() != null) {
            org.setIsDomesticDesc(dictService.getValue("area_list", String.valueOf(org.getIsDomestic())));
        } else {
            org.setIsDomestic("");
            org.setIsDomesticDesc("");
        }
        //IATA证书 和 营业执照Base64
        String officialLetter = org.getOfficialLetter();
        String offPath = officialLetter.substring(0,officialLetter.lastIndexOf("/")+1);
        String offName = officialLetter.substring(officialLetter.lastIndexOf("/") + 1);
        String imageBinary = null;
        try {
            imageBinary = ImgUtil.getImageBinary(offPath, offName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        org.setOfficialLetter(imageBinary);
        String busLicence = org.getBusLicence();
        String busPath = busLicence.substring(0,busLicence.lastIndexOf("/")+1);
        String busName = busLicence.substring(busLicence.lastIndexOf("/") + 1);
        String busBinary = null;
        try {
            busBinary = ImgUtil.getImageBinary(busPath, busName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        org.setBusLicence(busBinary);
        //查询注册联系人
        OrgaManVo regInfo = orgaService.selectMan(app.getOpcOrgaId());
        regInfo.setAuthDocumentTypeDesc(dictService.getValue("cert_type", String.valueOf(regInfo.getAuthDocumentType())));
        //查询其他注册联系人
        OrgaOtherManVo otherRegInfo = orgaService.selectOtherMan(app.getOpcOrgaId());
        if (otherRegInfo.getOtherPerCharge() == null){
            otherRegInfo.setOtherPerCharge("");
        }
        if (otherRegInfo.getOtherPerNumber() == null){
            otherRegInfo.setOtherPerNumber("");
        }
        if (otherRegInfo.getOtherInvoiceMailingAddr() == null){
            otherRegInfo.setOtherInvoiceMailingAddr("");
        }
        if (otherRegInfo.getOtherAuthDocumentNum() == null){
            otherRegInfo.setOtherAuthDocumentNum("");
        }
        if (otherRegInfo.getOtherAuthDocumentType() != null) {
            otherRegInfo.setOtherAuthDocumentTypeDesc(dictService.getValue("cert_type", String.valueOf(otherRegInfo.getOtherAuthDocumentType())));
        }else{
            otherRegInfo.setOtherAuthDocumentType("");
            otherRegInfo.setOtherAuthDocumentTypeDesc("");
        }
        //查询申请测试信息
        AppTestVo appTestVo = appService.selectAppInfo(id);
        if (appTestVo.getAppType() != null) {
            String appTypes = appTestVo.getAppType();
            appTestVo.setAppTypeDesc(getAppTypeNames(appTypes));
        }
        if (appTestVo.getPayMent() != null && !("").equals(appTestVo.getPayMent())) {
            appTestVo.setPayMentDesc(dictService.getValue("pay_ment", String.valueOf(appTestVo.getPayMent())));
        }
        if(appTestVo.getApplyFlow() == null){
            appTestVo.setApplyFlow(0L);
        }
        if(appTestVo.getApprovalFlow() == null){
            appTestVo.setApprovalFlow(0L);
        }
        //赋值有效期与限流
        if(testApplyDetail != null && isApproval){
            appTestVo.setTestBeginTime(testApplyDetail.getBeginTimeNew());
            appTestVo.setTestEndTime(testApplyDetail.getEndTimeNew());
            appTestVo.setApplyQps(Long.valueOf(testApplyDetail.getApplyFlow()));
            appTestVo.setApprovalQps(Long.valueOf(testApplyDetail.getApprovalFlow()));
        }

        //渠道申请接口路径
        String path = "/CeairDevService/ApiAuditNDC/ApiAuditNdcService.asmx/StartChaanelAuthFlow";
        // String resData = "";
        //查询产品信息集合 多产品分批发送审批
        int count = 0;
        List<ProdListVo> prodListVo = productService.selectProdList(id);

        for(ProdListVo prod: prodListVo) {
            prod.setPrivilegeLevelDesc(dictService.getValue("privilege_level", String.valueOf(prod.getPrivilegeLevel())));
            prod.setIsCostDesc(dictService.getValue("is_cost", String.valueOf(prod.getIsCost())));
            if(prod.getNote() == null){
                prod.setNote("");
            }
        }
        Map<String, List<ProdListVo>> map = prodListVo.stream().collect(Collectors.groupingBy(ProdListVo::getOwnSystem));
        for (Map.Entry<String, List<ProdListVo>> m : map.entrySet()) {
            String sysName = m.getKey();
            List<ProdListVo> list = m.getValue();
            ArrayList<ProdListVo> prolist = new ArrayList<>();
            for(ProdListVo data: list){
                prolist.add(data);
            }
            //产品类型
            String prodType = (("AI系统").equals(sysName)? "2": (("NDC系统").equals(sysName)? "1": "3"));
            HashMap<String, String> hashMap = new HashMap<String, String>();
            hashMap.put("title", "渠道申请");
            hashMap.put("busNo", String.valueOf(id));
            hashMap.put("appType", "1");
            hashMap.put("appTypeDesc", "渠道申请");
            hashMap.put("mode",approve.getModeType());
            hashMap.put("modeDesc",approve.getModeTypeDesc());
            hashMap.put("useruid",approve.getUseruid());
            hashMap.put("account",approve.getAccount());
            hashMap.put("realName",approve.getRealName());
            hashMap.put("prodType",prodType);
            hashMap.put("prodTypeName",sysName);
            Map<String, Object> map1 = new LinkedHashMap<>();
            map1.put("org", org);
            map1.put("regInfo", regInfo);
            map1.put("otherRegInfo", otherRegInfo);
            HashMap<String, Object> map2 = new HashMap();
            map2.put("orgData", map1);
            HashMap<String, Object> map3 = new HashMap();
            map3.put("appTestInfo", appTestVo);
            Map<String, Object> map6 = new LinkedHashMap<>();
            map6.put("pub", hashMap);
            map6.put("orgData", map1);
            map6.put("chnlData", map3);
            map6.put("productList", prolist);
            Map<String, Object> mapHead = new LinkedHashMap<>();
            Map<String, Object> postParameters = new LinkedHashMap<>();
            postParameters.put("Head", mapHead);
            postParameters.put("Body", map6);
            String resData = "";
            try {
                //返回响应报文
                resData = XmlData.getXml(path, postParameters);
            } catch (IOException e) {
                log.error("异常信息：{}", e);
            }
            //响应报文转成对象
            ResultAPI data = JSONObject.parseObject(resData, ResultAPI.class);
            //返回响应码
            String responseCode = data.getHead().getResponseCode();
            if ("9999".equals(responseCode)){
                return R.fail("此操作用户在系统中不存在!");
            }
            String type = approve.getType();
            String url = "/" + type;
            //根据系统名称查询id
            Sys sys = sysService.selectByName(sysName);
            Long productId = sys.getId();
            if (!insertProdApprove(data, id, productId, type, url)) {
                return R.status(false);
            }
        }
        //发起审批成功后改变状态为审批中
        app.setStatus(4);
        app.setApproveOpinion("");
        appService.updateById(app);
        return R.status(true);
    }

    /**
     * @param appTypes
     * @return java.lang.String
     * @Description 获取应用类型
     * @Author sjm
     * @Date 17:36 2020/3/7 0007
     **/
    private String getAppTypeNames(String appTypes) {
        String appTypeNames = ",";
        String[] appTypeArry = appTypes.split(",");
        for (String appType : appTypeArry) {
            Dict dict = new Dict();
            dict.setCode("app_type");
            dict.setDictKey(appType);
            List<Dict> list = dictService.list(Condition.getQueryWrapper(dict));
            if (list.size() == 1) {
                appTypeNames += list.get(0).getDictValue() + ",";
            }
        }
        if (appTypeNames.length() > 2) {
            appTypeNames = appTypeNames.substring(1, appTypeNames.length() - 1);
        }
        return appTypeNames;
    }

    /**
     * @param approve
     * @return com.dhcc.bpm.common.utils.ResultAPI
     * @Description 机构认证
     * @Author sjm
     * @Date 17:36 2020/3/7 0007
     **/
    private ResultAPI selectOrga(ApproveVO approve) {
        Long id = approve.getId();
        //查询机构信息
        OrgaInfoVo org = orgaService.selectOrgaInfo(id);
        //截取文件名
        String otherFiles = org.getOtherFiles();
        String otherFilesName = otherFiles.substring(otherFiles.lastIndexOf("/") + 1);
        org.setOtherFilesName(otherFilesName);
        org.setOrgaTypeDesc(dictService.getValue("orga_type", String.valueOf(org.getOrgaType())));
        org.setServiceTradeDesc(dictService.getValue("industry_type", String.valueOf(org.getServiceTrade())));
        if (org.getIsDomestic() != null) {
            org.setIsDomesticDesc(dictService.getValue("area_list", String.valueOf(org.getIsDomestic())));
        } else {
            org.setIsDomestic("");
            org.setIsDomesticDesc("");
        }
        //IATA证书 和 营业执照Base64
        String officialLetter = org.getOfficialLetter();
        String offPath = officialLetter.substring(0,officialLetter.lastIndexOf("/")+1);
        String offName = officialLetter.substring(officialLetter.lastIndexOf("/") + 1);
        String imageBinary = "";
        try {
            imageBinary = ImgUtil.getImageBinary(offPath, offName);
        } catch (Exception e) {
            log.error("图片异常信息：{}", e);
        }
        org.setOfficialLetter(imageBinary);
        String busLicence = org.getBusLicence();
        String busPath = busLicence.substring(0,busLicence.lastIndexOf("/")+1);
        String busName = busLicence.substring(busLicence.lastIndexOf("/") + 1);
        String busBinary = "";
        try {
            busBinary = ImgUtil.getImageBinary(busPath, busName);
        } catch (Exception e) {
            log.error("图片异常信息：{}", e);
        }
        org.setBusLicence(busBinary);
        //查询注册联系人
        OrgaManVo regInfo = orgaService.selectMan(id);
        regInfo.setAuthDocumentTypeDesc(dictService.getValue("cert_type", String.valueOf(regInfo.getAuthDocumentType())));
        //查询其他注册联系人
        OrgaOtherManVo otherRegInfo = orgaService.selectOtherMan(id);
        if (otherRegInfo.getOtherPerCharge() == null){
            otherRegInfo.setOtherPerCharge("");
        }
        if (otherRegInfo.getOtherPerNumber() == null){
            otherRegInfo.setOtherPerNumber("");
        }
        if (otherRegInfo.getOtherInvoiceMailingAddr() == null){
            otherRegInfo.setOtherInvoiceMailingAddr("");
        }
        if (otherRegInfo.getOtherAuthDocumentNum() == null){
            otherRegInfo.setOtherAuthDocumentNum("");
        }
        if (otherRegInfo.getOtherAuthDocumentType() != null) {
            otherRegInfo.setOtherAuthDocumentTypeDesc(dictService.getValue("cert_type", String.valueOf(otherRegInfo.getOtherAuthDocumentType())));
        }else{
            otherRegInfo.setOtherAuthDocumentType("");
            otherRegInfo.setOtherAuthDocumentTypeDesc("");
        }
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("org", org);
        map.put("regInfo", regInfo);
        map.put("otherRegInfo", otherRegInfo);
        HashMap<String, String> hashMap = new HashMap();
        hashMap.put("title", "机构认证");
        hashMap.put("busNo", String.valueOf(id));
        hashMap.put("appType", "1");
        hashMap.put("appTypeDesc", "机构接入");
        hashMap.put("mode",approve.getModeType());
        hashMap.put("modeDesc",approve.getModeTypeDesc());
        hashMap.put("useruid",approve.getUseruid());
        hashMap.put("account", approve.getAccount());
        hashMap.put("realName", approve.getRealName());
        Map<String, Object> map2 = new LinkedHashMap<>();
        map2.put("pub", hashMap);
        map2.put("orgData", map);
        Map<String, Object> mapHead = new LinkedHashMap<>();
        Map<String, Object> postParameters = new LinkedHashMap<>();
        postParameters.put("Head", mapHead);
        postParameters.put("Body", map2);
        //机构接口路径
        String path = "/CeairDevService/ApiAuditNDC/ApiAuditNdcService.asmx/StartApiProSubFlow";
        String resData = "";
        try {
            //返回响应报文
            resData = XmlData.getXml(path, postParameters);
        } catch (IOException e) {
            log.error("异常信息：{}", e);
        }
        //响应报文转成对象
        ResultAPI data = JSONObject.parseObject(resData, ResultAPI.class);
        return data;
    }

    /**
     * @param approve
     * @return com.dhcc.bpm.common.utils.ResultAPI
     * @Description Api发布
     * @Author sjm
     * @Date 17:37 2020/3/7 0007
     **/
    private ResultAPI selectApiInfo(ApproveVO approve) {
        //api发布类型
        String appType = approve.getAppType();
        //api批量发布id
        String apiIds = approve.getIds();
        String apiNo = null;
        String appTypeDesc = null;
        if("1".equals(appType)){
            appTypeDesc = "创建发布";
            apiNo = apiIds;
        }else{
            appTypeDesc = "API下线";
            apiNo = String.valueOf(approve.getId());
        }
        List<Long> apiIdz = Func.toLongList(apiNo);
        ArrayList<ApiListVo> apiList = new ArrayList<>();
        //系统名称
        String sysName = null;
        for(Long apiId: apiIdz){
            ApiListVo api = apiService.selectApiVoById(apiId);
            if (api.getRequestMethod() == null){
                api.setRequestMethod("");
            }else{
                api.setRequestMethod(dictService.getValue("request_method", String.valueOf(api.getRequestMethod())));
            }
            //访问协议描述
            api.setAccessProtocolDesc(dictService.getValue("gateway_access_protocol", String.valueOf(api.getAccessProtocol())));
            //是否需要回调地址描述
            api.setIsRequireCallbackUrlDesc(dictService.getValue("is_require_callback_url",String.valueOf(api.getIsRequireCallbackUrl())));
            //安全认证类型描述
            api.setSafeTypeDesc(dictService.getValue("safe_type",String.valueOf(api.getSafeType())));
            //报文类型描述
            api.setMessageTypeDesc(dictService.getValue("gateway_message_type",String.valueOf(api.getMessageType())));
            //权限等级描述
            api.setPrivilegeLevelDesc(dictService.getValue("privilege_level",String.valueOf(api.getPrivilegeLevel())));
            if (api.getIsCost() == null){
                api.setIsCostDesc("");
            }else{
                //是否收费描述
                api.setIsCostDesc(dictService.getValue("is_cost",String.valueOf(api.getIsCost())));
            }
            apiList.add(api);
            //获取系统产品名称
            Api byId = apiService.getById(apiId);
            Sys sys = new Sys();
            sys.setCreateDept(byId.getCreateDept());
            List<Sys> list = sysService.list(Condition.getQueryWrapper(sys));
            if(list.size() == 0){
                //选取基础产品的系统
                BaseProduct baseProduct = baseProductService.getById(byId.getBackserviceId());
                Sys sysById = sysService.getById(baseProduct.getOpcSysId());
                sysName = sysById.getSysName();
            }else{
                Sys sys1 = list.get(0);
                sysName = sys1.getSysName();
            }
        }
        //产品类型
        String prodType = (("AI系统").equals(sysName))? "2": (("NDC系统").equals(sysName)? "1": "3");
        HashMap<String,String> hashMap = new HashMap();
        hashMap.put("title","API发布");
        hashMap.put("busNo",apiNo);
        hashMap.put("appType",appType);
        hashMap.put("appTypeDesc",appTypeDesc);
        hashMap.put("mode",approve.getModeType());
        hashMap.put("modeDesc",approve.getModeTypeDesc());
        hashMap.put("useruid",approve.getUseruid());
        hashMap.put("account",approve.getAccount());
        hashMap.put("realName",approve.getRealName());
        hashMap.put("prodType",prodType);
        hashMap.put("prodTypeName",sysName);
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("pub",hashMap);
        map.put("apiList",apiList);
        Map<String, Object> mapHead = new LinkedHashMap<>();
        Map<String, Object> postParameters = new LinkedHashMap<>();
        postParameters.put("Head",mapHead);
        postParameters.put("Body",map);
        //api接口路径
        String path ="/CeairDevService/ApiAuditNDC/ApiAuditNdcService.asmx/StartApiPublishAdultFlow";
        String resData = "";
        try {
            //返回响应报文
            resData = XmlData.getXml(path, postParameters);
        } catch (IOException e) {
            log.error("响应异常：{}", e);
        }
        //响应报文转成对象
        ResultAPI data = JSONObject.parseObject(resData,ResultAPI.class);
        return data;
    }

    /**
     * @Description 产品发布
     * @Author sjm
     * @Date 10:45 2020/3/9 0009
     * @param approve
     * @return com.dhcc.bpm.common.utils.ResultAPI
     **/
    @Override
    public R commitTaskProduct(ApproveVO approve) {
        Long id = approve.getId();
        String type = approve.getType();
        String apiNo = null;
        //产品上线
        String apiIds = approve.getApiIds();
        //产品信息
        productListVo product = productService.selectProById(id);
        String prodType = (("AI系统").equals(product.getOwnSystem()))? "2": (("NDC系统").equals(product.getOwnSystem())? "1": "3");
        //根据id查询创建人和部门
        productListVo user = productService.selectUserById(id);
        product.setCreateUserName(user.getCreateUserName());
        product.setCreateDeptName(user.getCreateDeptName());
        //权限等级描述
        product.setPrivilegeLevelProdDesc(dictService.getValue("privilege_level",String.valueOf(product.getPrivilegeLevelProd())));
        //是否收费描述
        product.setIsCostProdDesc(dictService.getValue("is_cost",String.valueOf(product.getIsCostProd())));
        List<ApiListVo> listVos = product.getApiList();
        List<ApiListVo> lists = new ArrayList<>();
        //产品下线的所有api
        List<ProductApi> apiList = null;
        //产品发布类型
        String appType = approve.getAppType();
        String appTypeDesc = null;
        if("1".equals(appType)){
            appTypeDesc = "创建发布";
            apiNo = apiIds;
            List<Long> list = Func.toLongList(apiNo);
            list.forEach(apiId->{
                ApiListVo data = apiService.selectApiVoById(apiId);
                //访问协议描述
                data.setAccessProtocolDesc(dictService.getValue("gateway_access_protocol", String.valueOf(data.getAccessProtocol())));
                //是否需要回调地址描述
                data.setIsRequireCallbackUrlDesc(dictService.getValue("is_require_callback_url",String.valueOf(data.getIsRequireCallbackUrl())));
                //安全认证类型描述
                data.setSafeTypeDesc(dictService.getValue("safe_type",String.valueOf(data.getSafeType())));
                //报文类型描述
                data.setMessageTypeDesc(dictService.getValue("gateway_message_type",String.valueOf(data.getMessageType())));
                //权限等级描述
                data.setPrivilegeLevelDesc(dictService.getValue("privilege_level",String.valueOf(data.getPrivilegeLevel())));
                //是否收费描述
                data.setIsCostDesc(dictService.getValue("is_cost",String.valueOf(data.getIsCost())));
                lists.add(data);
            });
        }else{
            appTypeDesc = "下线";
            apiList= productApiService.productApiList(id);
            ArrayList<String> list1 = new ArrayList<>();
            if(apiList.size() > 0){
                for(ProductApi data : apiList){
                    Long apiId = data.getApiId();
                    list1.add(String.valueOf(apiId));
                }
                apiNo = StringUtils.join(list1, ",");
                List<Long> list = Func.toLongList(apiNo);
                list.forEach(apiId->{
                    ApiListVo data = apiService.selectApiVoById(apiId);
                    //访问协议描述
                    data.setAccessProtocolDesc(dictService.getValue("gateway_access_protocol", String.valueOf(data.getAccessProtocol())));
                    //是否需要回调地址描述
                    data.setIsRequireCallbackUrlDesc(dictService.getValue("is_require_callback_url",String.valueOf(data.getIsRequireCallbackUrl())));
                    //安全认证类型描述
                    data.setSafeTypeDesc(dictService.getValue("safe_type",String.valueOf(data.getSafeType())));
                    //报文类型描述
                    data.setMessageTypeDesc(dictService.getValue("gateway_message_type",String.valueOf(data.getMessageType())));
                    //权限等级描述
                    data.setPrivilegeLevelDesc(dictService.getValue("privilege_level",String.valueOf(data.getPrivilegeLevel())));
                    //是否收费描述
                    data.setIsCostDesc(dictService.getValue("is_cost",String.valueOf(data.getIsCost())));
                    lists.add(data);
                });
            }
        }
        product.setApiList(lists);
        HashMap<String,String> hashMap = new HashMap();
        hashMap.put("title","产品发布");
        hashMap.put("busNo",String.valueOf(id));
        hashMap.put("appType",appType);
        hashMap.put("appTypeDesc",appTypeDesc);
        hashMap.put("mode",approve.getModeType());
        hashMap.put("modeDesc",approve.getModeTypeDesc());
        hashMap.put("useruid",approve.getUseruid());
        hashMap.put("account",approve.getAccount());
        hashMap.put("realName",approve.getRealName());
        hashMap.put("prodType",prodType);
        hashMap.put("prodTypeName",product.getOwnSystem());
        Map<String, Object> map1 = new LinkedHashMap<>();
        map1.put("pub",hashMap);
        map1.put("product",product);
        Map<String, Object> mapHead = new LinkedHashMap<>();
        Map<String, Object> postParameters = new LinkedHashMap<>();
        postParameters.put("Head",mapHead);
        postParameters.put("Body",map1);
        String path = "/CeairDevService/ApiAuditNDC/ApiAuditNdcService.asmx/StartApiProductAdultFlow";
        String resData = "";
        try {
            //组成xml报文
            resData = XmlData.getXml(path, postParameters);
        } catch (IOException e) {
            log.error("组成xml报文异常：{}", e);
        }
        //响应报文转成对象
        ResultAPI data = JSONObject.parseObject(resData,ResultAPI.class);
        Head head = data.getHead();
        String responseCode = head.getResponseCode();
        if ("9999".equals(responseCode)){
            return R.fail("此操作用户在系统中不存在!");
        }
        Long[] apis = Convert.toLongArray(apiIds);
        ProductApi productApi = new ProductApi();
        productApi.setProductId(id);
        if ("0".equals(responseCode)){
            //流程ID
            Object body = data.getBody();
            Long processId = Long.valueOf(body.toString());
            Approve appro = new Approve();
            //变更发布状态
            Product prods = new Product();
            prods.setId(id);

            //查询看是否有次条记录
            ApproveVO appros = baseMapper.getApproById(id);
            //发布待审批
            if ("1".equals(appType)){

                //产品发布审核中
                prods.setStatus(0);
                for(Long apiId: apis){
                    //改变发布状态
                    productApi.setProductId(id);
                    productApi.setApiId(apiId);
                    productApi.setStatus(0);
                    productApiService.updateStatus(productApi);
                }
                if (appros !=null){
                    //更新原记录(未通过重新上线)
                    appros.setProcessId(processId);
                    appros.setUrl("/"+type+"/up");
                    appros.setApprovalStatus(0L);
                    baseMapper.updateById(appros);
                }else{
                    //产品上线
                    appro.setUrl("/"+type+"/up");
                    //插入数据到审批表
                    appro.setBusNo(id);
                    appro.setApprovalStatus(0L);
                    appro.setProcessId(processId);
                    appro.setType(type);
                    save(appro);
                }
            }else{
                //下线待审批
                if(apiList != null && apiList.size() > 0){
                    //产品下线审核中
                    prods.setStatus(5);
                    apiList.forEach(prod->{
                        prod.setStatus(5);
                        productApiService.updateById(prod);
                    });
                }
                if (appros !=null){
                    //更新原记录
                    appros.setProcessId(processId);
                    appros.setApprovalStatus(0L);
                    appros.setUrl("/"+type+"/down");
                    baseMapper.updateById(appros);
                }else{
                    //产品下线
                    appro.setUrl("/"+type+"/down");
                    //插入数据到审批表
                    appro.setBusNo(id);
                    appro.setApprovalStatus(0L);
                    appro.setProcessId(processId);
                    appro.setType(type);
                    save(appro);
                }
            }
            productService.updateById(prods);
        }else {
            return R.status(false);
        }
        return R.status(true);
    }

    /**
     * @Description 同步数据
     * @Author sjm
     * @Date 21:44 2020/3/11 0011
     * @param opinionType
     * @param opinion
     * @param entity
     * @return com.dhcc.bpm.common.utils.ResResult
     **/
    @Override
    public ResResult refreshData(String opinionType, String opinion, Approve entity) {
        String type = entity.getType();
        Long busNo = entity.getBusNo();
        Integer opinionTypeInt = null;
        Long opcUserId = null;
        //消息推送名称
        String infoName =null;
        if("1".equals(opinionType)){
            //审批通过
            opinionTypeInt = 1;
        }else{
            //审批未通过
            opinionTypeInt = 2;
        }
        // Integer opinionTypeInt = (opinionType == "0") ? 1 : 2;
        //opinionType = (opinionType == "0") ? "1" : "2";
        switch (type) {
            case "api":
                String url = entity.getUrl();
                String apiUrl = url.substring(url.lastIndexOf("/") + 1);
                if("up".equals(apiUrl)){
                    //api上线
                    // 更新中间表
                    IssueApi issueApiQuery = new IssueApi();
                    issueApiQuery.setId(busNo);
                    List<IssueApi> issueApis = issueApiService.selectByCondition(issueApiQuery);
                    // 更新api审批结果
                    for (IssueApi issueApi1 : issueApis) {
                        Api api = apiService.getById(issueApi1.getApiId());
                        api.setStatus(opinionTypeInt);
                        api.setId(issueApi1.getApiId());
                        apiService.updateById(api);
                        // 审批通过插入路由信息
                        if("1".equals(opinionType)){
                            log.info("api审批通过");
                            //生产环境添加路由
//                            GatewayRoute route = new GatewayRoute();
//                            route.setOpcApiId(api.getId().toString());
//                            route.setBackServiceId(api.getAtomicServiceId().toString());
//                            route.setEnv("1");
//                            String[] gatewayIds = api.getOpcGatewayId().split(",");
//                            Long gatewayId = Long.valueOf(gatewayIds[0]);
//                            route.setOpcGatewayId(gatewayId);
//                            route.setRouteConfig("[{\"predicateValue\":\"" + api.getApiPath() + "\",\"name\":\"Path\"}]");
//                            //路由过滤器
//                            if(api.getBackserviceReqUrl() != null){
//                                route.setFilters("[{\"filterValue\":\"" + api.getBackserviceReqUrl() + "\",\"name\":\"SetPath\"}]");
//                            }
//                            gatewayRouteService.save(route);
//
//                            // 沙箱环境添加路由
//                            GatewayRoute sandboxRoute = new GatewayRoute();
//                            sandboxRoute.setOpcApiId(api.getId().toString());
//                            sandboxRoute.setBackServiceId(api.getAtomicServiceId().toString());
//                            // 环境类型 2:沙箱环境
//                            sandboxRoute.setEnv("2");
//                            String[] gatewayIdTests = api.getOpcGatewayIdTest().split(",");
//                            Long gatewayIdTest = Long.valueOf(gatewayIdTests[0]);
//                            sandboxRoute.setOpcGatewayId(gatewayIdTest);
//                            sandboxRoute.setRouteConfig("[{\"predicateValue\":\"" + api.getApiPathTest() + "\",\"name\":\"Path\"}]");
//                            gatewayRouteService.save(sandboxRoute);
//                            route.setId(null);


//                            List<Gateway> gatewayList = gatewayService.list(Condition.getQueryWrapper(gateway));
//                            if(gatewayList.size() > 0){
//                                for(Gateway gate :gatewayList){
//                                    route.setEnv("2");
//                                    route.setOpcGatewayId(gate.getId());
//                                    route.setRouteConfig("[{\"predicateValue\":\"" + api.getApiPathTest() + "\",\"name\":\"Path\"}]");
//                                    gatewayRouteService.save(route);
//                                    route.setId(null);
//                                }
//                            }
                            //api升级发邮件通知
                            if ("3".equals(api.getIsUpgrade())){
                                //将api修改为未升级
                                api.setIsUpgrade("1");
                                apiService.updateById(api);
                                if(isSendFlag){
                                    List<AppApi> list = appApiService.selectByApiId(api.getId());
                                    log.info("AppApi：{}" , list.toString());
                                    for (AppApi appApi: list){
                                        App app =  appService.getById(appApi.getOpcAppId());
                                        Product product = productService.getById(appApi.getOpcProductId());
                                        api = apiService.getById(api.getId());
                                        log.info("渠道邮箱：{}" , app.getPrpEmail());
                                        if (app != null && app.getPrpEmail() != null){
                                            String mailTitle = appEmailConfig.getTitle() + "api下线通知";
                                            String msg = "亲爱的用户您好！\r\n 您订阅的[" + product.getProductName() + "]产品中的[" + api.getApiName() + "]API已下线，详情请登录开放门户查看。对您造成的不便敬请谅解！";
                                            Boolean bool = emailUtils.sendEmail( mailTitle, app.getPrpEmail(), mailTitle, msg);
                                            log.info("api升级通知ota结果:{}" , bool);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    issueApiService.updateStatus(busNo);

                    //刷新Api和刷新路由
                    refreshApi();
                }else{
                    //api下线
                    Api api = new Api();
                    IssueApi byId = issueApiService.getIssueApiById(busNo);
                    api.setId(byId.getApiId());
                    if (("1").equals(opinionType)) {
                        log.info("api下线审批通过");
                        // 审批通过
                        api.setStatus(6);
                        boolean updated = apiService.updateById(api);
                        if(isSendFlag){
                            List<AppApi> list = appApiService.selectByApiId(api.getId());
                            log.info("AppApi：{}" , list.toString());
                            for (AppApi appApi: list){
                                App app =  appService.getById(appApi.getOpcAppId());
                                Product product = productService.getById(appApi.getOpcProductId());
                                api = apiService.getById(api.getId());
                                log.info("渠道邮箱：{}" , app.getPrpEmail());
                                if (app != null && app.getPrpEmail() != null){
                                    String mailTitle = appEmailConfig.getTitle() + "api下线通知";
                                    String msg = "亲爱的用户您好！\r\n 您订阅的[" + product.getProductName() + "]产品中的[" + api.getApiName() + "]API已下线，详情请登录开放门户查看。对您造成的不便敬请谅解！";
                                    boolean bool = emailUtils.sendEmail( mailTitle, app.getPrpEmail(), mailTitle, msg);
                                    log.info("api下线通知ota结果:{}" , bool);
                                }
                            }
                        }

                        //刷新Api
                        refreshApi();
                    }else{
                        // 审批不通过
                        api.setStatus(1);
                        boolean updated = apiService.updateById(api);
                    }
                }
                break;
            case "product":
                String proUrl = entity.getUrl();
                String prodUrl = proUrl.substring(proUrl.lastIndexOf("/") + 1);
                if("up".equals(prodUrl)){
                    //产品上线
                    //更新产品发布状态
                    Product prods = new Product();
                    prods.setId(busNo);
                    prods.setStatus(opinionTypeInt);
                    productService.updateById(prods);
                    //产品API关联
                    ProductApi productApi = new ProductApi();
                    productApi.setProductId(busNo);
                    productApi.setStatus(opinionTypeInt);

                    //审批通过, 生成文档目录
                    Product product = productService.getById(busNo);
                    DocDirectory docDirectory = new DocDirectory();
                    docDirectory.setDocName(product.getProductName() + " v" + product.getProductVersion());
                    docDirectory.setDocCode(product.getProductCode());
                    docDirectory.setParentId("0");
                    docDirectory.setUrl("#");
                    docDirectory.setDocType("2");
                    docDirectory.setDescribe(product.getDescribe());
                    DocDirectory isNull = iDocDirectoryService.getOne(Condition.getQueryWrapper(docDirectory));
                    // 表中已存在产品信息则不再插入
                    if (isNull == null) {
                        iDocDirectoryService.save(docDirectory);
                    }
                    // 产品Api接口信息集
                    List<ApiBO> apiBOS = productApiService.listRelatedApi(busNo);
                    for (ApiBO apiBO : apiBOS) {
                        DocDirectory docApi = iDocDirectoryService.findByDocCode(apiBO.getApiCode(), product.getProductCode(), apiBO.getId());
                        if(docApi == null){
                            docApi = new DocDirectory();
                        }
                        docApi.setDocCode(apiBO.getApiCode());
                        docApi.setParentId(product.getProductCode());
                        docApi.setDocName(apiBO.getApiName() + " v" + apiBO.getApiVersion());
                        docApi.setUrl(apiBO.getFileFullPath());
                        docApi.setDocType("3");
                        docApi.setDescribe(apiBO.getDescribe());
                        iDocDirectoryService.saveOrUpdate(docApi);
                    }
                    productApiService.updateAllStatus(productApi);
                    // 产品升级发送邮件通知
                    if (3 == product.getIsUpgrade()) {
                        //将产品修改为未升级
                        product.setIsUpgrade(1L);
                        productService.updateById(prods);
                        if(isSendFlag){
                            List<App> appLists = appService.listByProductId(busNo);
                            for(App app : appLists){
                                // 发送邮件通知
                                String mailTitle = appEmailConfig.getTitle() + product.getProductName() + "产品下线通知";
                                String msg = "尊敬的用户，您好！\r\n" + "您订阅的产品：[" + product.getProductName() + " ]已升级，详情请登录开放门户查看。对您造成的不便敬请谅解！！";
                                if(app.getPrpEmail() != null){
                                    emailUtils.sendEmail( mailTitle, app.getPrpEmail(), mailTitle, msg);
                                }
                            }
                        }
                    }
                }else{
                    //产品下线
                    Product product = new Product();
                    ProductApi productApi = new ProductApi();
                    productApi.setProductId(busNo);
                    Product productInfo = productService.getById(busNo);
                    if (opinionType.equals("1")) {
                        // 审批通过
                        product = productService.getById(busNo);
                        // 更新 opc_product
                        product.setStatus(6);
                        productService.updateById(product);
                        // 更新 opc_product_api
                        productApi.setStatus(6);
                        productApi.setIsDeleted(1);
                        int apiUpdated = productApiService.updateAllStatus(productApi);
                        log.info("产品下线下线相关文档！" );
                        // 更新 opc_doc_directory
//                        iDocDirectoryService.removeDocByProductCode(product.getProductCode());
                        int docNum = iDocDirectoryService.updateDocByProductCode(product.getProductCode());
                        log.info("产品下线同时下线相关文档数量：{}", docNum);
                        if(isSendFlag){
                            // 产品下线发送邮件通知
                            List<App> appLists = appService.listByProductId(productInfo.getId());
                            for(App app : appLists){
                                // 发送邮件通知
                                String mailTitle = appEmailConfig.getTitle() + productInfo.getProductName() + "产品下线通知";
                                String msg = "尊敬的用户，您好！\r\n" + "您订阅的产品：[" + productInfo.getProductName() + " ]已下线，详情请登录开放门户查看。对您造成的不便敬请谅解！！";
                                if(app.getPrpEmail() != null){
                                    emailUtils.sendEmail( mailTitle, app.getPrpEmail(), mailTitle, msg);
                                }
                            }
                        }

                    }else{
                        // 审批拒绝
                        product.setId(busNo);
                        product.setStatus(1);
                        productService.updateById(product);
                        productApi.setStatus(1);
                        productApiService.updateApiStatus(productApi);
                    }
                }
                break;
            case "orga":
                Orga orga = orgaService.getById(busNo);
                if(opinionTypeInt == 1){
                    //机构认证审批通过 并启用
                    orga.setAuthFlag("1");
                    orga.setOrgaStatus("1");
                }else{
                    orga.setAuthFlag("2");
                }
                orgaService.saveOrUpdate(orga);
                //消息推送到门户
                opcUserId = orga.getOpcUserId();
                infoName = orga.getOrgaName();
                messagePush(type,infoName,opcUserId,opinionTypeInt);
                break;
            case "orgaChange":
                // 机构信息变更
                Orga newOrg = orgaService.getById(busNo);
                Orga oldOrg = new Orga();
                if (1 == opinionTypeInt) {
                    // 审批通过
                    // 将变更最新数据copy到旧数据中并更新(下面为前台支持修改的信息)
                    oldOrg.setId(newOrg.getParentId());
                    oldOrg.setOfficialWeb(newOrg.getOfficialWeb());
                    oldOrg.setOrgaType(newOrg.getOrgaType());
                    oldOrg.setPostCode(newOrg.getPostCode());
                    oldOrg.setServiceTrade(newOrg.getServiceTrade());
                    oldOrg.setOrgaArea(newOrg.getOrgaArea());
                    oldOrg.setOfficialLetter(newOrg.getOfficialLetter());
                    oldOrg.setOtherFiles(newOrg.getOtherFiles());
                    oldOrg.setPerCharge(newOrg.getPerCharge());
                    oldOrg.setPerNumber(newOrg.getPerNumber());
                    oldOrg.setAuthDocumentType(newOrg.getAuthDocumentType());
                    oldOrg.setAuthDocumentNum(newOrg.getAuthDocumentNum());
                    oldOrg.setInvoiceMailingAddr(newOrg.getInvoiceMailingAddr());
                    oldOrg.setOtherPerCharge(newOrg.getOtherPerCharge());
                    oldOrg.setOtherPerNumber(newOrg.getOtherPerNumber());
                    oldOrg.setOtherAuthDocumentType(newOrg.getOtherAuthDocumentType());
                    oldOrg.setOtherAuthDocumentNum(newOrg.getOtherAuthDocumentNum());
                    oldOrg.setOtherInvoiceMailingAddr(newOrg.getOtherInvoiceMailingAddr());
                    //
                    orgaService.updateById(oldOrg);
                    // 更改变更数据认证状态
                    newOrg.setAuthFlag("1");
                    orgaService.updateById(newOrg);
                } else {
                    // 审批拒绝
                    newOrg.setAuthFlag("2");
                    orgaService.updateById(newOrg);
                }
                //消息推送到门户
                opcUserId = newOrg.getOpcUserId();
                infoName = newOrg.getOrgaName();
                messagePush(type,infoName,opcUserId,opinionTypeInt);
                break;
            case "app":
                // 应用创建
                App app = appService.getById(busNo);
                // 申请测试环境
                TestApply tApplyQuery = new TestApply();
                tApplyQuery.setAppId(busNo);
                TestApply testApply = testApplyService.getOne(Condition.getQueryWrapper(tApplyQuery));
                testApply.setApproveStatus(opinionType);

                appService.updateOpc_app_api(busNo, opinionType);
                testApplyService.updateById(testApply);
                // 审批通过，生成沙箱
                if (opinionTypeInt == 1) {
                    //添加渠道权限
                    List<Api> api=  apiService.selectApiByAppId(app.getId());
                    ArrayList<String> list = new ArrayList<>();
                    for(Api data: api){
                        String apiScope = data.getApiScope();
                        if (list.contains(apiScope)){
                            continue;
                        }else{
                            list.add(apiScope);
                        }
                    }
                    String scopes = StringUtils.join(list, ",");
                    //已审批
                    app.setStatus(6);
                    app.setApproveOpinion(opinion);
                    app.setScope(scopes);
                    app.setTestScope(scopes);
                    //更新表状态
                    appService.updateById(app);
                    // 申请测试环境成功调用 1代表测试
                    app.setEnv(1L);
                    appService.approvalCreateAppInfo(app);
                    if (isApproval){
                        //通过覆盖数据
                        testApply.setTestBeginTime(testApply.getBeginTimeNew());
                        testApply.setTestEndTime(testApply.getEndTimeNew());
                        testApply.setApplyQps(Long.valueOf(testApply.getApplyFlow()));
                        testApply.setApprovalQps(Long.valueOf(testApply.getApprovalFlow()));
                        testApplyService.updateById(testApply);
                    }
                }else{
                    //应用审批拒绝
                    app.setStatus(2);
                    app.setApproveOpinion(opinion);
                    appService.updateById(app);
                }
                //消息推送到门户
                Orga byId = orgaService.getById(app.getOpcOrgaId());
                opcUserId = byId.getOpcUserId();
                infoName = app.getAppName();
                messagePush(type,infoName,opcUserId,opinionTypeInt);
                break;
            case "appChange":
                // 应用信息变更
                App newApp = appService.getById(busNo);
                App oldApp = new App();
                if (1 == opinionTypeInt) {
                    // 审批通过
                    // 将变更最新数据copy到旧数据中并更新(下面为前台支持修改的信息)
                    oldApp.setId(newApp.getPid());
                    oldApp.setDescribe(newApp.getDescribe());
                    oldApp.setPerCharge(newApp.getPerCharge());
                    oldApp.setPrpTel(newApp.getPrpTel());
                    oldApp.setAppType(newApp.getAppType());
                    oldApp.setAppValidTime(newApp.getAppValidTime());
                    oldApp.setAppState("1");
                    appService.updateById(oldApp);

                    //更新产品api表
                    appApiService.deleteByAppId(newApp.getPid(), "2");
                    List<AppApi> lists = appApiService.selectByAppId(busNo);
                    for (AppApi data : lists){
                        //改变接口状态
                        data.setValidStatus("1");
                        appApiService.updateById(data);
                        //替换旧的接口数据
                        data.setOpcAppId(newApp.getPid());
                        appApiService.save(data);
                    }
                    // 更改认证状态
                    newApp.setOperationType(2L);
                    newApp.setApproveOpinion(opinion);
                    newApp.setStatus(1);
                    appService.updateById(newApp);
                    if(isApproval){
                        //更新申请测试数据
                        //通过覆盖数据
                        TestApply test = new TestApply();
                        test.setAppId(newApp.getPid());
                        TestApply testApplys = testApplyService.getOne(Condition.getQueryWrapper(test));
                        testApplys.setTestBeginTime(testApplys.getBeginTimeNew());
                        testApplys.setTestEndTime(testApplys.getEndTimeNew());
                        testApplys.setApplyQps(Long.valueOf(testApplys.getApplyFlow()));
                        testApplys.setApprovalQps(Long.valueOf(testApplys.getApprovalFlow()));
                        testApplyService.updateById(testApplys);
                    }

                    //渠道应用权限刷新
                    App accessApp = appService.getById(newApp.getPid());
                    String testAppId = accessApp.getTestAppId();
                    //刷新token
                    Collection<OAuth2AccessToken> findTokensByClientId = tokenStore.findTokensByClientId(testAppId);
                    findTokensByClientId.forEach(p -> redisMessageSender.sendMessageToChannel("TOKEN", readAccessToken(p.getValue()).getValue()));
                } else {
                    // 审批拒绝
                    oldApp.setId(newApp.getPid());
                    oldApp.setAppState("2");
                    appService.updateById(oldApp);
                    newApp.setOperationType(2L);
                    newApp.setApproveOpinion(opinion);
                    newApp.setStatus(2);
                    appService.updateById(newApp);
                }
                //消息推送到门户
                Orga appChange = orgaService.getById(newApp.getOpcOrgaId());
                opcUserId = appChange.getOpcUserId();
                infoName = newApp.getAppName();
                messagePush(type,infoName,opcUserId,opinionTypeInt);
                break;
            case "produceapply":
                //应用申请生产环境
                ProduceApply produceApply = produceApplyService.getById(busNo);
                // 审批通过，生成沙箱
                if (opinionTypeInt == 1) {
                    //状态已审批
                    produceApply.setApproveStatus("6");
                    // 申请生产环境成功调用 0代表生产
                    App app1 = new App();
                    app1.setId(produceApply.getAppId());
                    app1.setEnv(0L);
                    appService.approvalCreateAppInfo(app1);
                    if(isApproval){
                        //更新数据
                        produceApply.setTestBeginTime(produceApply.getBeginTimeNew());
                        produceApply.setTestEndTime(produceApply.getEndTimeNew());
                        produceApply.setApplyQps(Long.valueOf(produceApply.getApplyFlow()));
                        produceApply.setApprovalQps(Long.valueOf(produceApply.getApprovalFlow()));
                    }
                }else{
                    //审批状态未通过
                    produceApply.setApproveStatus(opinionType);
                }
                produceApply.setApproveOpinion(opinion);
                produceApply.setApproveTime(DateUtils.asDate(LocalDateTime.now()));
                produceApplyService.updateById(produceApply);
                //消息推送到门户
                Orga pro = orgaService.getById(produceApply.getOrgaId());
                App apps = appService.getById(produceApply.getAppId());
                opcUserId = pro.getOpcUserId();
                infoName = apps.getAppName();
                messagePush(type,infoName,opcUserId,opinionTypeInt);
                break;
            case "onlineapply":
                //应用上线
                //审批通过
                OnlineApply onlineApply = onlineApplyService.getById(busNo);
                onlineApply.setApproveStatus(opinionType);
                onlineApply.setApproveOpinion(opinion);
                onlineApply.setApproveTime(DateUtils.asDate(LocalDateTime.now()));
                onlineApplyService.updateById(onlineApply);
                //消息推送到门户
                Orga onlineOrga = orgaService.getById(onlineApply.getOrgaId());
                App appOnline = appService.getById(onlineApply.getAppId());
                opcUserId = onlineOrga.getOpcUserId();
                infoName = appOnline.getAppName();
                messagePush(type,infoName,opcUserId,opinionTypeInt);
                break;
            default:
                break;
        }
        return ResResult.success();
    }

    /**
     * @Description 获取token
     * @Author sjm
     * @Date 17:50 2020/4/2 0002
     * @param token
     * @return org.springframework.security.oauth2.common.OAuth2AccessToken
     **/
    @GetMapping("/readToken")
    public OAuth2AccessToken readAccessToken(String token) {
        OAuth2AccessToken readAccessToken = tokenStore.readAccessToken(token);
        return readAccessToken;
    }
    /**
     * @Description 审批后消息推送
     * @Author sjm
     * @Date 11:33 2020/3/31 0031
     * @param type
     * @param infoName
     * @param opcUserId
     * @param opinionTypeInt
     * @return void
     **/
    private void messagePush(String type,String infoName, Long opcUserId, Integer opinionTypeInt) {
        //发送推送回复消息
        Message message = new Message();
        String msgCode = serialNumberService.generateSerialNumberByModelCode("opc_access_control");
        //消息推送名称
        String msgName = null;
        //消息内容
        String msgContent = null;
        switch (type){
            case "orga":
                msgName = infoName + "机构认证通知";
                if (opinionTypeInt == 1){
                    //审批通过
                    msgContent = "尊敬的用户,您的"+infoName + "信息已认证通过,请注意查看通知!";
                }else{
                    //审批不通过
                    msgContent = "尊敬的用户,您的"+infoName + "信息认证未通过,请注意查看通知!";
                }
                break;
            case "orgaChnage":
                msgName = infoName + "机构变更通知";
                if (opinionTypeInt == 1){
                    //审批通过
                    msgContent = "尊敬的用户,您的"+infoName + "机构信息变更已通过,请注意查看通知!";
                }else{
                    //审批不通过
                    msgContent = "尊敬的用户,您的"+infoName + "机构信息变更未通过,请注意查看通知!";
                }
                break;
            case "app":
                msgName = infoName + "渠道申请通知";
                if (opinionTypeInt == 1){
                    //审批通过
                    msgContent = "尊敬的用户,您的"+infoName + "渠道信息申请已通过,请注意查看通知!";
                }else{
                    //审批不通过
                    msgContent = "尊敬的用户,您的"+infoName + "渠道信息申请未通过,请注意查看通知!";
                }
                break;
            case "appChange":
                msgName = infoName + "渠道变更通知";
                if (opinionTypeInt == 1){
                    //审批通过
                    msgContent = "尊敬的用户,您的"+infoName + "渠道信息变更已通过,请注意查看通知!";
                }else{
                    //审批不通过
                    msgContent = "尊敬的用户,您的"+infoName + "渠道信息变更未通过,请注意查看通知!";
                }
                break;
            case "produceapply":
                msgName = infoName + "生产验证通知";
                if (opinionTypeInt == 1){
                    //审批通过
                    msgContent = "尊敬的用户,您的"+infoName + "渠道信息生产验证已通过,请注意查看通知!";
                }else{
                    //审批不通过
                    msgContent = "尊敬的用户,您的"+infoName + "渠道信息生产验证未通过,请注意查看通知!";
                }
                break;
            case "onlineapply":
                msgName = infoName + "上线申请通知";
                if (opinionTypeInt == 1){
                    //审批通过
                    msgContent = "尊敬的用户,您的"+infoName + "渠道信息上线申请已通过,请注意查看通知!";
                }else{
                    //审批不通过
                    msgContent = "尊敬的用户,您的"+infoName + "渠道信息上线申请未通过,请注意查看通知!";
                }
                break;
            default:
                break;
        }
        message.setMsgCode(msgCode);
        message.setMsgType("1");
        message.setReceiver(opcUserId.toString());
        message.setMsgName(msgName);
        message.setMsgContent(msgContent);
        message.setDescribe("回复" + msgName + "消息");
        message.setPushStatus(2);
        if(messageService.saveOrUpdate(message)){
            MessageUtils utils = new MessageUtils();
            utils.sendMessage("开放平台",message.getId().toString());
            log.info(String.valueOf(utils));
        }
    }

    /**
     * @Description 刷新API
     * @Author sjm
     * @Date 11:33 2020/3/25 0025
     * @param
     * @return org.springblade.core.tool.api.R
     **/
    private R refreshApi() {
        try {
            String message = redisMessageSender.format(ConfigType.API.name(), "刷新接口配置");
            redisMessageSender.sendMessageToGateway(null, message);
            String route = redisMessageSender.format(ConfigType.ROUTE.name(), "刷新接口路由配置");
            redisMessageSender.sendMessageToGateway(null, route);
            return R.status(true);
        }catch (Exception e){
            log.error("刷新产品配置失败:{}", e);
            return R.status(false);
        }
    }

    /**
     * @param processId
     * @return com.dhcc.bpm.modules.workflow.entity.Approve
     * @Description 查询原数据
     * @Author sjm
     * @Date 20:46 2020/3/4 0004
     **/
    @Override
    public Approve selectApprove(Long processId) {
        return baseMapper.selectApprove(processId);
    }

    /**
     * @Description 根据id查询
     * @Author sjm
     * @Date 18:40 2020/3/10 0010
     * @param busNo
     * @return com.dhcc.bpm.modules.workflow.vo.ApproveVO
     **/
    @Override
    public ApproveVO getApproById(Long busNo) {
        return baseMapper.getApproById(busNo);
    }

    /**
     * @Description 根据业务编号和产品id查询集合
     * @Author sjm
     * @Date 16:18 2020/3/31 0031
     * @param busNo
     * @param productId
     * @return com.dhcc.bpm.modules.workflow.entity.Approve
     **/
    @Override
    public Approve getApproByProdAppId(Long busNo, Long productId) {
        return baseMapper.getApproByProdAppId(busNo,productId);
    }
}
